<?php
use think\cache\driver\Redis;

function invoke_fraud_api(array $params, $timeout = 500, $connection_timeout = 500) {

  $api_url = "https://apitest.tongdun.cn/riskService";

  return curl_td($api_url, $params, $timeout, $connection_timeout);
}
 
function rule_detail($sequence_id ,array $params, $timeout = 500, $connection_timeout = 500){

  $api_url = 'https://apitest.tongdun.cn/risk/rule.detail/v3.1?partner_code=qhwd&partner_key=66f2bc1432c44823953de3551e26ef72&sequence_id='.$sequence_id;

  return curl_td($api_url, $params, $timeout, $connection_timeout);

}

/**
 * 贷前申请 - 生成报告id
 * @return [type] [description]
 */
function preloan_apply($params, $is_test = true){

  $api_url = 'http://api.qhweidai.com/api/watermelon';
  $res = http_post($api_url,$params);
  return json_decode($res,true);

}

/**
 * 贷前申请 - 报告详情
 * @return [type] [description]
 */
function preloan_report($param, $is_test = true){

  $api_url = 'http://api.qhweidai.com/api/look_watermelon';

  $res = http_post($api_url,$param);
  return json_decode($res,true);

}

/**
 * 贷前申请 - 风险报告
 * @return [type] [description]
 */
function preloan_report_risk($param){

  $api_url = 'http://api.qhweidai.com/api/Riskgrade';
  $res = http_post($api_url,$param);
  return json_decode($res,true);
}


/**
 * GET 请求
 * @param string $url
 */
function http_get($url){
  $oCurl = curl_init();
  if(stripos($url,"https://")!==FALSE){
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  }
  curl_setopt($oCurl, CURLOPT_URL, $url);
  curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  $sContent = curl_exec($oCurl);
  $aStatus = curl_getinfo($oCurl);
  curl_close($oCurl);
  if(intval($aStatus["http_code"])==200){
    return $sContent;
  }else{
    return false;
  }
}

/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
function http_post($url,$param='',$post_file=false){
  $oCurl = curl_init();
  if(stripos($url,"https://")!==FALSE){
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  }

  if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
    $is_curlFile = true;
  } else {
    $is_curlFile = false;
    if (defined('CURLOPT_SAFE_UPLOAD')) {
      curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
    }
  }
  if (is_string($param)) {
    $strPOST = $param;
  }elseif($post_file) {
    if($is_curlFile) {
      foreach ($param as $key => $val) {
        if (substr($val, 0, 1) == '@') {
          $param[$key] = new \CURLFile(realpath(substr($val,1)));
        }
      }
    }
    $strPOST = $param;
  } else {
    $aPOST = array();
    foreach($param as $key=>$val){
      $aPOST[] = $key."=".urlencode($val);
    }
    $strPOST =  join("&", $aPOST);
  }
  curl_setopt($oCurl, CURLOPT_URL, $url);
  curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  curl_setopt($oCurl, CURLOPT_POST,true);
  curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  $sContent = curl_exec($oCurl);
  $aStatus = curl_getinfo($oCurl);
  curl_close($oCurl);
  if(intval($aStatus["http_code"])==200){
    return $sContent;
  }else{
    return false;
  }
}




function curl_td($api_url, $params, $timeout, $connection_timeout){

  $options = array(
      CURLOPT_POST => 1,            // 请求方式为POST
      CURLOPT_URL => $api_url,      // 请求URL
      CURLOPT_RETURNTRANSFER => 1,  // 获取请求结果
    // -----------请确保启用以下两行配置------------
    // CURLOPT_SSL_VERIFYPEER => 1,  // 验证证书
    // CURLOPT_SSL_VERIFYHOST => 2,  // 验证主机名
    // -----------否则会存在被窃听的风险------------
      CURLOPT_POSTFIELDS => http_build_query($params) // 注入接口参数
  );
  if (defined("CURLOPT_TIMEOUT_MS")) {
    $options[CURLOPT_NOSIGNAL] = 1;
    $options[CURLOPT_TIMEOUT_MS] = $timeout;
  } else {
    $options[CURLOPT_TIMEOUT] = ceil($timeout / 1000);
  }
  if (defined("CURLOPT_CONNECTTIMEOUT_MS")) {
    $options[CURLOPT_CONNECTTIMEOUT_MS] = $connection_timeout;
  } else {
    $options[CURLOPT_CONNECTTIMEOUT] = ceil($connection_timeout / 1000);
  }
  $ch = curl_init();

  // curl_setopt ($ch, CURLOPT_CAINFO, getcwd().'/Public/cet/cacert.pem');


  curl_setopt_array($ch, $options);
  if(!($response = curl_exec($ch))) {
    // 错误处理，按照同盾接口格式fake调用结果
    return array(
        "success" => "false",
        "reason_code" => "000:调用API时发生错误[".curl_error($ch)."]"
    );
  }
  curl_close($ch);
  return json_decode($response, true);

}

function get_name_by_report_id($report_id){

  $name = M('preloan_apply','td_')->where(array('report_id'=>$report_id))->getfield('name');
  return $name?$name:'error!';
}

//短信统计
function smsTj()
{
  $redis  = new Redis();
  $redis->select(15);
  $data = date("Y-m-d");
  // $data = date("Y-m-d",strtotime("-1 day"));
  $data.="_guodu";
  $exists = $redis->exists($data);
  #每日初始化
  $initData=array('renqijie'=>0,'bjj'=>0,'rrjkw'=>0,'wdy'=>0,'ygbk'=>0);
  if(!$exists){
      #设置前一天的统计数据过期时间
      $yesterday = date("Y-m-d",strtotime("-1 day"))."_guodu";
      $redis->setTimeout($yesterday,3600*24*30);
      #初始化 今天的数据
      $redis -> hMset( $data,$initData);
  }
  #当前平台 field 自增1
  $redis->hincrby($data, 'ygbk', 1);
}

/**
 * cookies加密函数
 * @param string 加密后字符串
 */
function encrypt($data, $key = 'kls8in1e') 
{ 
    $prep_code = serialize($data); 
    $block = mcrypt_get_block_size('des', 'ecb'); 
    if (($pad = $block - (strlen($prep_code) % $block)) < $block) { 
        $prep_code .= str_repeat(chr($pad), $pad); 
    } 
    $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB); 
    return base64_encode($encrypt); 
} 

/**
 * cookies 解密密函数
 * @param array 解密后数组
 */
function decrypt($str, $key = 'kls8in1e') 
{ 
    $str = base64_decode($str); 
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); 
    $block = mcrypt_get_block_size('des', 'ecb'); 
    $pad = ord($str[($len = strlen($str)) - 1]); 
    if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) { 
        $str = substr($str, 0, strlen($str) - $pad); 
    } 
    return unserialize($str); 
}
